import { ref, onUnmounted } from 'vue';
import { WebSocketService, WsReadyState } from '@/utils/websocket.core';

export default function useWebSocket(url: string, options: {
  onMessage?: (data: string) => void;
  autoConnect?: boolean;
} = {}) {
  const messages = ref<string[]>([]);
  const status = ref<WsReadyState>(WsReadyState.CLOSED);
  const error = ref<Event | null>(null);

  const wsService = new WebSocketService(url, {
    onOpen: () => status.value = WsReadyState.OPEN,
    onClose: () => status.value = WsReadyState.CLOSED,
    onError: (err) => {
      error.value = err;
      status.value = WsReadyState.ERROR;
    },
    onMessage: (msg) => {
      try {
        // const data = JSON.parse(msg)
        messages.value.push(msg);
        options.onMessage?.(msg);
      } catch (e) {
        console.error('WebSocket message parse error:', e);
      }
    }
  });

  // 自动连接
  if (options.autoConnect !== false) {
    wsService.connect();
  }

  // 组件卸载时关闭连接
  onUnmounted(() => {
    wsService.close();
  });

  // 发送消息
  const send = (data: string | object) => {
    wsService.send(data);
  };

  // 手动重连
  const reconnect = () => {
    wsService.close();
    wsService.connect();
  };

  return {
    messages,
    status,
    error,
    send,
    connect: wsService.connect.bind(wsService),
    close: wsService.close.bind(wsService),
    reconnect
  };
}
